#!/bin/bash

user=`getprop persist.sys.qiku_log_user`
case "$user" in
    1)
    setprop persist.sys.qiku_log_user 0
    exit 0
    ;;
esac

BB=/system/bin/busybox
DATE="$BB date"
GREP="$BB grep"
TAIL="$BB tail"
CUT="$BB cut"
SED="$BB sed"
PRINTF="$BB printf"

SDCARD_LOG_DIR="/sdcard/admin"
BACKUP_LOG_DIR="/data/misc/backup"
DATA_STR=
TIME_SDCARD_LOG_DIR=
DATA_DIR=

LOG_DIR_RENAME=
[ -x "$BB" ] || exit

#COPY THE LOG TO TEMP BACKUP
mkdir -p $BACKUP_LOG_DIR
mv /data/misc/logd/* $BACKUP_LOG_DIR

#REMOVE THE LOGD TO CATCH THE NEW LOG
rm -rf /data/misc/logd/*

#LUNCH NEW SERVICE TO CATCH LOG
start logcat_main
#start logcat_system
start logcat_radio
start logcat_events
#start logcat_crash
start logcat_klogd
start qseelog

#WIAT SDCARD TO READY
sleep 50

#CATCH QXDM LOG
qxdm=`getprop persist.sys.qiku_log_qxdm`
case "$qxdm" in
    1)
    start qiku_diag_mdlog_start
    ;;
esac

#GET FILE NAME TO SDCARD
if ! [ -n "$OUT_DIR" -a -d "$OUT_DIR" ]; then
    date=$(date "+%y%m%d_%H%M%S")
    DATA_DIR="CQ_${date}"
    TIME_SDCARD_LOG_DIR="$SDCARD_LOG_DIR/$DATA_DIR"
fi

#CREATE SDCARD/ADMIN FILE
mkdir -p $TIME_SDCARD_LOG_DIR

#MUST COPY THE NET THEN START TCP
mv $SDCARD_LOG_DIR/net $TIME_SDCARD_LOG_DIR/net

#CATCH TCP NET LOG
net=`getprop persist.sys.qiku_log_net`
case "$net" in
    1)
    mkdir -p $SDCARD_LOG_DIR/net
    start logcat_tcp
    ;;
esac

#BEGIN TO COPY LOG TO SDCARD/ADMIN
mkdir -p $TIME_SDCARD_LOG_DIR/app
cp -rf $BACKUP_LOG_DIR/* $TIME_SDCARD_LOG_DIR/app/
cp -rf /data/system/dropbox $TIME_SDCARD_LOG_DIR
cp -rf /data/tombstones $TIME_SDCARD_LOG_DIR
cp -rf /data/anr $TIME_SDCARD_LOG_DIR
cp -rf /sys/fs/pstore $TIME_SDCARD_LOG_DIR
uptime > $TIME_SDCARD_LOG_DIR/app/uptime.txt

mkdir -p "$TIME_SDCARD_LOG_DIR/hci"
cp -rf /data/misc/bluetooth/logs/ $TIME_SDCARD_LOG_DIR/hci/

mkdir -p "$TIME_SDCARD_LOG_DIR/wlan"
cp -rf /sdcard/wlan_logs/ $TIME_SDCARD_LOG_DIR/wlan/
rm -rf /sdcard/wlan_logs/*

#MODIFY THE TCPLOG NAME
for tcpname in $( ls $TIME_SDCARD_LOG_DIR/net/* );do
    mv $tcpname $tcpname.pcap
done

tar -zcvf $TIME_SDCARD_LOG_DIR.tar.gz -C /sdcard/admin $DATA_DIR
rm -rf $TIME_SDCARD_LOG_DIR/

#REMOVE OLD LOG
rm -rf /data/system/dropbox/*
rm -rf /data/tombstones/*
rm -rf /data/anr/*
rm -rf /data/misc/backup/*
